package http_proxy_middleware

import (
	"gitee.com/zhoulvvv/my_go_gateway/dao"
	"gitee.com/zhoulvvv/my_go_gateway/middleware"
	"gitee.com/zhoulvvv/my_go_gateway/reverse_proxy"
	"gitee.com/zhoulvvv/my_go_gateway/services"
	"github.com/gin-gonic/gin"
	"github.com/pkg/errors"
)

// HTTP 反向代理中间件
func HTTPReverseProxyModeMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		serviceInterface, ok := c.Get("service")
		if !ok {
			middleware.ResponseError(c, 2001, errors.New("【服务不存在】service not found"))
			c.Abort()
			return
		}
		service := serviceInterface.(*dao.ServiceDetail)
		// 获取到负载均衡器
		lb, err := services.LoadBalancerHandler.GetLoadBalancer(c, service)
		if err != nil {
			middleware.ResponseError(c, 2001, errors.New("【获取负载均衡器失败】err: "+err.Error()))
			c.Abort()
			return
		}
		// 获取http连接池
		transport, err := services.LoadBalancerHandler.GetTransport(c, service)
		if err != nil {
			middleware.ResponseError(c, 2001, errors.New("【获取http连接池】err: "+err.Error()))
			c.Abort()
			return
		}
		proxy := reverse_proxy.NewLoadBalanceReverseProxy(c, lb, transport)
		// 执行代理
		proxy.ServeHTTP(c.Writer, c.Request)
	}
}
